/**
 * 
 */
package managers;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import persistence.Message;
import persistence.ObjectFactory;
import persistence.Utilisateur;

import ressources.Props;

/**
 * @author Administrateur
 *
 */
public class ComManager {

	public ComManager() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * Init the url connection
	 * @return HttpUrlConnection
	 */
	public static HttpURLConnection getServerConnection(){
		URL url;
		HttpURLConnection connexion = null;
		try {
			url = new URL(Props.getProps().getProperty("url.server"));
			connexion = (HttpURLConnection) url.openConnection();
			connexion.setDoOutput(true);
			connexion.setDoInput(true);
			connexion.setUseCaches(false);
			connexion.setRequestMethod("POST");
			connexion.setAllowUserInteraction(true);
			connexion.setRequestProperty("Content-Type", "text/xml");
			//connexion.setRequestProperty("Accept", "application/xml");
			connexion.connect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return connexion;	
	}

	/**
	 * Send a request to a server
	 * @param outputStream - the outputStream
	 * @param m
	 * @throws JAXBException 
	 * @throws IOException 
	 */
	public static void sendRequest(OutputStream out, Message msg) throws JAXBException, IOException{
		JAXBContext jc = JAXBContext.newInstance(Message.class,ObjectFactory.class,Utilisateur.class);
		Marshaller m = jc.createMarshaller();
		m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.marshal(msg,out);
		out.close();		
	}

	/**
	 * Receive response
	 * @param in
	 * @return
	 * @throws JAXBException 
	 * @throws FileNotFoundException 
	 */
	public static Message receiveResponse(InputStream in) throws JAXBException, FileNotFoundException{
		return (Message) JAXBContext.newInstance(Message.class,ObjectFactory.class,Utilisateur.class).createUnmarshaller().unmarshal(in);
	}
}
